package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.query.TravelCondition;
import cn.wolfcode.luowowo.query.TravelQuery;
import cn.wolfcode.luowowo.repository.TravelRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.ITravelService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
// 游记
@Service
//@Transactional mongodb事务必须复制集方式
public class TravelServiceImpl implements ITravelService {

    //spring-data-mongodb中的查询方式有两种repository(不能分页操作)和template
    //Spring-boot集成redis持久化数据库
    @Autowired
    private TravelRepository repository;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IDestinationService destinationService;


    @Override
    public void save(Travel travel) {

        travel.setId(null);
        repository.save(travel);
    }

    @Override
    public void delete(String id) {

        repository.deleteById(id);
    }

    @Override
    public void update(Travel travel) {

        repository.save(travel);
    }

    @Override
    public Travel get(String id) {

        Travel travel = repository.findById(id).orElse(null);

        // 前端控制台报图片错误
        if(travel !=null){
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }

        return travel;
    }

    @Override
    public List<Travel> listAll() {
        return repository.findAll();
    }

    //区域分页查询(高级查询)
    @Override
    public Page<Travel> query(TravelQuery qo) {
        Query query = new Query();

        // 2.目的地页面:游记排出行天数下拉框(出行天数)
        TravelCondition day = qo.getDay();
        if (day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        // 3.目的地页面:游记下拉框.(人均消费)
        TravelCondition perExpendType = qo.getPerExpendType();
        if (perExpendType != null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpendType.getMin()).lte(perExpendType.getMax()));
        }


        // 1.目的地页面:游记分页
        if(StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }


        Pageable pageable = null;
        // 4.目的地页面:游记排序(最新或最热的)
        if(qo.getOrderType()==1){//最新(创建时间最后的)
            pageable = PageRequest.of(qo.getCurrentPage()-1,
                    qo.getPageSize(), Sort.Direction.DESC,"createTime");
        }else if(qo.getOrderType()==2){//最热(点击量最高的)
            pageable = PageRequest.of(qo.getCurrentPage()-1,
                    qo.getPageSize(), Sort.Direction.DESC,"viewnum");
        }else {//兜底
            pageable = PageRequest.of(qo.getCurrentPage()-1,
                    qo.getPageSize(), Sort.Direction.ASC,"_id");
        }


        // 1.解决autor(UserInfo对象)为空问题,实际上页面控制台headImgUrl(头像报错)
        Page<Travel> page = DBHelper.query(template, Travel.class, query, pageable);
        // 2.页面缺少用户对象信息(应把用户对象设置到游记对象中)
        for (Travel travel : page) {
            String userId = travel.getUserId();
            UserInfo userInfo = userInfoService.get(userId);
            travel.setAuthor(userInfo);
        }

        return page;
    }

    // 添加按钮:添加/更新
    @Override
    public void saveOrUpdate(Travel travel) {
        // 旅游日记页面:发表按钮.(保存/更新.避免数据丢失)

        // 1.缺少:目的地名称
        Destination dest = destinationService.get(travel.getDestId());
        // 重置目的地名称
        travel.setDestName(dest.getName());
        // 2.缺少:当前用户Id(当前用户id必须登录才能有)
        // 用户Id(表现层设置了这里就不用设置了)

        // 3.缺少:最后更新时间
        travel.setLastUpdateTime(new Date());

        if(StringUtils.hasLength(travel.getId())){

            this.update(travel);//更新
        }else{
            // 创建时间
            travel.setCreateTime(new Date());

            this.save(travel);//保存
        }
    }

    // 游记管理模块：审核通过按钮(改变状态)
    @Override
    public void audit(String id, int state) {
        // 1.审核流程(条件)
        // 2.判断是否满足审核条件(判断审核的状态)
        // 游记存在才能审核(首先获取游记)
        Travel travel = this.get(id);
        if(travel==null){
            throw new LogicException("参数异常");
        }
        if(travel.getState() != Travel.STATE_WAITING){
            throw new LogicException("游记不是待审核状态,不允许审核!");
        }
        // 3.审核通过需要做什么
        if(state == Travel.STATE_RELEASE){
            // ①修改状态为审核通过状态
            travel.setState(Travel.STATE_RELEASE);
            // ②修改发布时间
            travel.setReleaseTime(new Date());
            // ③最后更新时间
            travel.setLastUpdateTime(new Date());
            // 若是和钱有关系的④记录审核信息(审核人, 审核时间,审核状态,审核备注)

            // ④修改游记
            this.update(travel);
        }else if(state == Travel.STATE_REJECT){
            // 4.审核拒绝之后需要做什么
            // ①修改状态为拒绝状态
            travel.setState(Travel.STATE_REJECT);
            // ②修改发布时间(设置为null)
            travel.setReleaseTime(null);
            // ③最后更新时间
            travel.setLastUpdateTime(new Date());
            // 若是和钱有关系的④记录审核信息(审核人, 审核时间,审核状态,审核备注)


            // ④修改游记
            this.update(travel);
        }else{//其他状态
            throw new LogicException("状态不对");
        }
    }

    // 查某个目的地下游记点击量前3的文篇
    @Override
    public List<Travel> travelsViewnumTop3(String destId) {

        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        List<Travel> list = repository.findByDestId(destId,pageable);

        return list;
    }

    // 通过目的地名称查询游记
    @Override
    public List<Travel> queryByDestName(String destName) {

        List<Travel> travels = repository.findByDestName(destName);
        for (Travel travel : travels) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
            travel.setDest(destinationService.get(travel.getDestId()));
        }
        return travels;
    }

}
